var get = require('../../utils/getRequest')
var post = require('../../utils/postRequest')
const api = require('../../utils/api')
const ecUI = require('../../utils/ecUI.js')
const ecBLE = require('../../utils/ecBLE.js')
let ctx
let isCheckRevHex = false
let isCheckScroll = true
let isCheckSendHex = false
let timer = null
Page({
  data: {
    deviceListData: [],
    deviceListDataShow: [],
    deviceSn: null,
    productList: [],
    deviceMsg: null,
    sheetShow: false,
    sheetActions: [
      {
        id: '01',
        name: '在线支付',
      },
      {
        id: '02',
        name: '信用分支付',
      },
    ],
    twoballLog: api.twoballLog,
    ball01Log: api.ball01Log,
    ball02Log: api.ball02Log,
    salesGridList: [],
    rentGridList: [],
    showRentGridList: [],
    giveBackList: [],
    popupShow: false,
    buyHtml: '',
    buyItem: null,
    rentHtml: '',
    rentItem: null,
    dealType: null,
    giveBackIndex: null,
    errorBallTimes: 1,
    receiveData: '',
  },
  onShow(res) {
    get.getRequest(null, api.getAllProductList, {}).then((res) => {
      ctx.setData({
        productList: res.data,
      })
      ctx.getDevice()
    })
    setTimeout(() => {
      ctx.openBluetoothAdapter()
    }, 100)
    timer = setInterval(function () {
      var commd = '{SQLID}'
      ctx.btSendTap(commd)
    }, 1000)
  },
  onLoad(options) {
    if (api.openId == null) {
      wx.login({
        success: (res) => {
          var code = res.code
          var data = {
            code: code,
          }
          get.getRequest(null, api.getOpenIdByCode, data).then((res) => {
            if (res.code == 200) {
              api.openId = res.data.openId
            }
          })
        },
      })
    }
    var deviceSn = options.deviceSn
    ctx = this
    ctx.setData({
      deviceSn: deviceSn,
    })
    setInterval(() => {
      ctx.setData({
        deviceListDataShow: ctx.data.deviceListData,
      })
    }, 400)
  },
  getDevice() {
    var data = {
      deviceSn: ctx.data.deviceSn,
    }
    get.getRequest(null, api.getDeviceByDeviceSn, data).then((res) => {
      ctx.setData({
        deviceMsg: res.data,
      })
      ctx.initSalesGrid()
      ctx.initRentGrid()
    })
  },
  initSalesGrid() {
    //初始化出售的格子
    var salesGridList = []
    var deviceMsg = ctx.data.deviceMsg
    console.log(deviceMsg,123456);
    var gridNumber = deviceMsg.gridNumber
    for (var i = 1; i <= gridNumber; i++) {
      var name01 = 'grid0' + i + 'StateType'
      var stateType = deviceMsg[name01]
      if (stateType != '1') continue
      var name02 = 'grid0' + i + 'ProductId'
      var productIdStr = deviceMsg[name02]
      var arry = productIdStr.split(',')
      var arry01 = arry[0]
      var arry02 = arry[1]
      if (arry01 != '1') continue
      var obj = ctx.getProductMsg(arry02, i)
      let newObj = Object.assign({}, obj)
      salesGridList.push(newObj)
    }
    console.log('销售的格子：', salesGridList)
    ctx.setData({
      salesGridList: salesGridList,
    })
  },
  initRentGrid() {
    //初始化租用的格子
    var rentGridList = []
    var deviceMsg = ctx.data.deviceMsg
    var gridNumber = deviceMsg.gridNumber
    console.log('格子数量B：' + gridNumber)
    for (var i = 1; i <= gridNumber; i++) {
      var name01 = 'grid0' + i + 'StateType'
      var stateType = deviceMsg[name01]
      if (stateType != '1') continue
      var name02 = 'grid0' + i + 'ProductId'
      var productIdStr = deviceMsg[name02]
      var arry = productIdStr.split(',')
      var arry01 = arry[0]
      var arry02 = arry[1]
      if (arry01 != '2') continue
      var obj = ctx.getProductMsg(arry02, i)
      let newObj = Object.assign({}, obj)
      rentGridList.push(newObj)
    }
    console.log('出租的格子：', rentGridList)
    ctx.setData({
      rentGridList: rentGridList,
    })
  },
  initShowRentGridList(obj) {
    //初始化显示可以租用的格子
    var rentGridList = this.data.rentGridList
    var gridList = obj.data
    var showRentGridList = []
    console.log(rentGridList)
    for (var i = 0; i < gridList.length; i++) {
      if (gridList[i].state != '6') continue
      for (var j = 0; j < rentGridList.length; j++) {
        if (i == rentGridList[j].index - 1) {
          var obj = rentGridList[j]
          obj.num = gridList[i].num
          let newObj = Object.assign({}, obj)
          showRentGridList.push(newObj)
          break
        }
      }
    }
    console.log('ssssssssssssssssss')
    console.log('租用的格子对象：', showRentGridList)
    ctx.setData({
      showRentGridList: showRentGridList,
    })
  },
  initgiveBackList(obj) {
    //初始化可以归还的格子
    var rentGridList = this.data.rentGridList
    var gridList = obj.data
    var giveBackList = []
    console.log(rentGridList)
    for (var i = 0; i < gridList.length; i++) {
      if (gridList[i].state != '1' && gridList[i].state != '2') continue
      for (var j = 0; j < rentGridList.length; j++) {
        if (i == rentGridList[j].index - 1) {
          var obj = rentGridList[j]
          obj.num = gridList[i].num
          let newObj = Object.assign({}, obj)
          giveBackList.push(newObj)
          break
        }
      }
    }
    console.log('ssssssssssssssssss')
    console.log('归还的格子：', giveBackList)
    ctx.setData({
      giveBackList: giveBackList,
    })
  },
  getProductMsg(productId, index) {
    var productList = ctx.data.productList
    for (var i = 0; i < productList.length; i++) {
      if (productId == productList[i].productId) {
        productList[i].index = index
        productList[i].name = '' + ctx.gridName(index)
        return productList[i]
      }
    }
    return null
  },
  gridName(index) {
    if (index == 1) {
      return '①'
    } else if (index == 2) {
      return '②'
    } else if (index == 3) {
      return '③'
    } else if (index == 4) {
      return '④'
    } else if (index == 5) {
      return '⑤'
    } else if (index == 6) {
      return '⑥'
    }
  },
  openRentBallDetail(event) {
    var rentHtml = event.currentTarget.dataset.item.productDesc
    var rentItem = event.currentTarget.dataset.item
    console.log('rentHtml:', rentHtml)
    console.log('rentItem:', rentItem)
    rentHtml = rentHtml.replace(
      /<img/gi,
      '<img style="max-width:100%;height:auto;display:block" '
    )
    this.setData({
      rentHtml: rentHtml,
      rentItem: rentItem,
      dealType: '2',
      popupShow: true,
    })
  },
  rentBall(event) {
    console.log(event)
    var antecedentMoney = event.currentTarget.dataset.item.antecedentMoney
    var data = {
      deviceSn: ctx.data.deviceSn,
      washballSn: event.currentTarget.dataset.item.num,
      index: event.currentTarget.dataset.item.index,
      openId: api.openId,
      perhourPrice: event.currentTarget.dataset.item.productPrice,
      payType: 'payscore',
    }
    ctx.tenancy(data)
    // wx.showModal({
    //   title: '提示信息',
    //   showCancel: true,
    //   content: "收取" + antecedentMoney + "元押金，归还扣除租金后将退回剩余的金额",
    //   success(res) {
    //     if (res.confirm) {
    //       ctx.tenancy(data);
    //     }
    //   }
    // })
  },
  async tenancy(data) {
    const res = await get.getRequest(null, api.initRentPay, data)
    var extraData = {
      mch_id: res.data.mchId,
      package: res.data.package,
      timestamp: res.data.timestamp,
      sign_type: res.data.signType,
      nonce_str: res.data.nonceStr,
      sign: res.data.paySign,
    }
    wx.openBusinessView({
      businessType: 'wxpayScoreUse',
      extraData,
      success(res) {
        if (res.extraData.query_id) {
          var index = data.index
          var commd = '{"lock":"0' + index + '"' + '}'
          ctx.btSendTap(commd)
          commd = '{SQLID}'
          ctx.onPopupClose()
          setInterval(() => {
            var com = '{SQLID}'
            ctx.btSendTap(com)
          }, 1000)
        }
      },
      fail(res) {
        console.log('租用失败')
      },
    })
  },
  launchRentBallPay(data) {
    get.getRequest(null, api.initRentPay, data).then((res) => {
      if (res.code == 200) {
        console.log(res)
        wx.requestPayment({
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.package,
          signType: res.data.signType,
          paySign: res.data.paySign,
          success(res) {
            var index = data.index
            var commd = '{"lock":"0' + index + '"' + '}'
            console.log('commd======' + commd)
            ctx.btSendTap(commd)
            commd = '{SQLID}'
            console.log('commd======' + commd)
            ctx.onPopupClose()
            setInterval(() => {
              var com = '{SQLID}'
              ctx.btSendTap(com)
            }, 1000)
          },
          fail(res) {},
        })
      } else {
        wx.showModal({
          title: '提示信息',
          showCancel: true,
          content: res.msg,
        })
      }
    })
  },
  openBuyBallDetail(event) {
    var buyHtml = event.currentTarget.dataset.item.productDesc
    var buyItem = event.currentTarget.dataset.item
    console.log('html:', buyHtml)
    console.log('buyItem:', buyItem)
    buyHtml = buyHtml.replace(
      /<img/gi,
      '<img style="max-width:100%;height:auto;display:block" '
    )
    this.setData({
      buyHtml: buyHtml,
      buyItem: buyItem,
      dealType: '1',
      popupShow: true,
    })
  },
  buyBall(event) {
    console.log('buyBall:', event)
    var deviceListDataShow = ctx.data.deviceListDataShow
    if (deviceListDataShow.length == 0) {
      wx.showToast({
        title: '蓝牙断开了连接，请重新扫码进入',
      })
      return
    }
    var data = {
      deviceSn: ctx.data.deviceSn,
      index: event.currentTarget.dataset.item.index,
      productId: event.currentTarget.dataset.item.productId,
      openId: api.openId,
    }
    var html = event.currentTarget.dataset.item.productDesc
    console.log('html:', html)
    html = html.replace(
      /<img/gi,
      '<img style="max-width:100%;height:auto;display:block" '
    )
    this.setData({
      html: html,
    })
    get.getRequest(null, api.initBuyPay, data).then((res) => {
      if (res.code == 200) {
        console.log(res)
        wx.requestPayment({
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.package,
          signType: res.data.signType,
          paySign: res.data.paySign,
          success(res) {
            var index = event.currentTarget.dataset.item.index
            var commd = '{"lock":"0' + index + '"' + '}'
            console.log('commd======' + commd)
            ctx.onPopupClose()
            ctx.btSendTap(commd)
            ctx.updateBuyForDevice(index)
          },
          fail(res) {},
        })
      }
    })
  },
  updateBuyForDevice(index) {
    var newsalesGridList = []
    var salesGridList = ctx.data.salesGridList
    var deviceType = this.data.deviceMsg.deviceType
    console.log('deviceType========' + deviceType)
    for (var i = 0; i < salesGridList.length; i++) {
      if (index == salesGridList[i].index) continue
      newsalesGridList.push(salesGridList[i])
    }
    ctx.setData({
      salesGridList: newsalesGridList,
    })
    var data = {
      deviceSn: ctx.data.deviceSn,
      index: index,
    }
    if (deviceType == '2') {
      get.getRequest(null, api.saveDeviceBallBuyState, data).then((res) => {
        console.log('---------------')
        console.log(res)
      })
    }
  },
  openGrid() {
    var index = 1
    var commd = '{"lock":"0' + index + '"' + '}'
    console.log('commd======' + commd)
    ctx.btSendTap(commd)
  },
  openPopup(event) {
    this.setData({
      popupShow: true,
    })
  },
  onPopupClose() {
    this.setData({
      popupShow: false,
    })
  },
  // 归还
  giveBackBall(event) {
    var giveBackIndex = event.currentTarget.dataset.item.index
    wx.showModal({
      title: '提示信息',
      showCancel: true,
      content:
        '点击确认后，不要离开本页面，将打格子，把租用的洗衣球放进去选择的格子中，充上电并关上锁',
      success(res) {
        if (res.confirm) {
          ctx.setData({
            giveBackIndex: giveBackIndex,
          })
          var commd = '{"lock":"0' + giveBackIndex + '"' + '}'
          console.log('commd======' + commd)
          ctx.btSendTap(commd)
          wx.showLoading({
            title: '等待处理中',
          })
        }
      },
    })
  },
  dealGiveBackBall(obj) {
    var state = obj.state
    var id = obj.id
    var washballSn = obj.num
    var giveBackIndex = '0' + this.data.giveBackIndex
    var deviceSn = this.data.deviceSn
    if ((id == giveBackIndex && state == '5') || state == '6') {
      var data = {
        washballSn: washballSn,
        deviceSn: deviceSn,
        openId: api.openId,
      }
      get
        .getRequest(null, api.dealGiveBackBall, data)
        .then((res) => {
          if (res.code == 200) {
            wx.showModal({
              title: '提示信息',
              showCancel: false,
              content: res.msg,
              success(res) {
                if (res.confirm) {
                  ctx.setData({
                    giveBackIndex: null,
                  })
                  var commd = '{SQLID}'
                  ctx.btSendTap(commd)
                }
              },
            })
          } else {
            wx.showModal({
              title: '提示信息',
              showCancel: false,
              content: res.msg,
              success(res) {
                if (res.confirm) {
                  ctx.setData({
                    giveBackIndex: null,
                  })
                  var commd = '{"lock":"0' + giveBackIndex + '"' + '}'
                  ctx.btSendTap(commd)
                }
              },
            })
          }
        })
        .finally((res) => {
          wx.hideLoading()
        })
    }
  },
  dealErrorRentBall(obj) {
    var list = obj.data
    var dealList = []
    var test = []
    for (var i = 0; i < list.length; i++) {
      test.push(list[i].num)
      if (list[i].state == '5' || list[i].state == '6') {
        dealList.push(list[i].num)
      }
    }
    console.log('球的编号A：', test)
    if (dealList.length > 0) {
      var washballSnStr = ''
      for (var i = 0; i < dealList.length; i++) {
        washballSnStr = washballSnStr + dealList[i] + ','
      }
      console.log('球的编号：', washballSnStr)
      var deviceSn = this.data.deviceSn
      var data = {
        washballSnStr: washballSnStr,
        deviceSn: deviceSn,
        openId: api.openId,
      }
      wx.showLoading({
        title: '检查历史订单中',
      })
      get
        .getRequest(null, api.dealErrorRentBallList, data)
        .then((res) => {
          console.log('检查订单：', res)
          console.log('检查订单：', res.code)
          if (res.code == 200) {
            ctx.setData({
              errorBallTimes: 0,
            })
            var commd = '{SQLID}'
            ctx.btSendTap(commd)
          }
        })
        .finally((res) => {
          wx.hideLoading()
        })
    } else {
      ctx.setData({
        errorBallTimes: 0,
      })
      var commd = '{SQLID}'
      ctx.btSendTap(commd)
    }
  },
  onPullDownRefresh: function () {
    ctx.setData({
      deviceListData: [],
    })
    ctx.setData({
      deviceListDataShow: [],
    })
    setTimeout(() => {
      wx.stopPullDownRefresh()
      ctx.openBluetoothAdapter()
    }, 500)
  },
  listViewTap(device) {
    ecUI.showLoading('设备连接中')
    ecBLE.onBLEConnectionStateChange((res) => {
      ecUI.hideLoading()
      if (res.ok) {
        ecBLE.stopBluetoothDevicesDiscovery()
      } else {
        ecUI.showModal(
          '提示',
          '连接失败,errCode=' + res.errCode + ',errMsg=' + res.errMsg
        )
      }
    })
    //const device = event.currentTarget.dataset.name
    ecBLE.createBLEConnection(device.id).then((res) => {
      console.log(res)
      ctx.onState()
      ecUI.hideLoading()
    })
  },
  onState() {
    isCheckScroll = true
    isCheckRevHex = false
    isCheckSendHex = false
    //on disconnect
    ecBLE.onBLEConnectionStateChange(() => {
      // ecUI.showModal('提示', '设备断开连接')
    })
    //receive data
    ecBLE.onBLECharacteristicValueChange((str, strHex) => {
      let data = ctx.data.receiveData + str
      console.log(str)
      console.log('----------传入数据----------------------')
      console.log(data)
      var mydata = data.replace('[{{', '[{')
      mydata = mydata.replace('"id:"', '"id":"')
      console.log(mydata)
      var obj = null
      clearInterval(timer)
      try {
        obj = JSON.parse(mydata)
        ctx.setData({
          receiveData: '',
        })
        wx.hideLoading()
      } catch (e) {
        console.log(e)
        ctx.setData({
          receiveData: mydata,
        })
        return
      }

      console.log('获取的对象内容：' + obj)
      if (obj.type == '3' && ctx.data.errorBallTimes <= 0) {
        //读取全部格子状态
        ctx.initShowRentGridList(obj)
        ctx.initgiveBackList(obj)
      }
      if (obj.type == '3' && ctx.data.errorBallTimes > 0) {
        ctx.dealErrorRentBall(obj)
      }
      if (obj.type == '2' && ctx.data.giveBackIndex != null) {
        //单个格子状态上报
        ctx.dealGiveBackBall(obj)
      }

      //ctx.setData({ textRevData: data })
    })
  },

  btSendTap(sendData) {
    let tempSendData = sendData.replace(/\n/g, '\r\n')
    ecBLE.writeBLECharacteristicValue(tempSendData, false)
  },
  openBluetoothAdapter() {
    ecBLE.onBluetoothAdapterStateChange((res) => {
      if (res.ok) {
        console.log('Bluetooth adapter ok')
        ctx.startBluetoothDevicesDiscovery()
      } else {
        ecUI.showModal(
          '提示',
          `Bluetooth adapter error | ${res.errCode} | ${res.errMsg}`,
          () => {
            if (res.errCode === 30001) {
              wx.openSystemBluetoothSetting()
            }
            if (res.errCode === 30003) {
              wx.openAppAuthorizeSetting()
            }
            if (res.errCode === 30004) {
              //跳转到小程序设置界面
              wx.openSetting()
            }
          }
        )
      }
    })
    ecBLE.openBluetoothAdapter()
  },
  startBluetoothDevicesDiscovery() {
    console.log('start search')
    ecBLE.onBluetoothDeviceFound((res) => {
      for (const item of ctx.data.deviceListData) {
        if (item.id === res.id) {
          item.name = res.name
          item.rssi = res.rssi
          return
        }
      }
      let manufacturer = ''
      if (res.name.length === 11 && res.name.startsWith('@')) {
        manufacturer = 'eciot'
      }
      if (res.name.length === 15 && res.name.startsWith('BT_')) {
        manufacturer = 'eciot'
      }
      if (res.name == ctx.data.deviceSn) {
        ctx.data.deviceListData.push({
          id: res.id,
          name: res.name,
          rssi: res.rssi,
          manufacturer,
        })
        ctx.listViewTap(res)
      }
    })
    ecBLE.startBluetoothDevicesDiscovery()
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log('------------onUnload----------------------')
    ecBLE.onBLEConnectionStateChange(() => {})
    ecBLE.onBLECharacteristicValueChange(() => {})
    ecBLE.closeBLEConnection()
    wx.hideLoading()
  },
})
